package main.controller.admin;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Projections;
import main.RequestHelper;
import main.GlobalConfig;
import main.TimeHelper;
import main.database.AccountHelper;
import main.database.DatabaseMan;
import main.database.NotifyHelper;
import org.bson.Document;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class AuthorListPageController {
    @RequestMapping (value = "authorlist")
    public String authorList(ModelMap modelMap, HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);
        boolean isLogin = AccountHelper.isExistFromUUID(uuid);
        String account = AccountHelper.getAccountInfoFromUUID(uuid);

        modelMap.put("isLogin", isLogin);
        if (!isAdmin) {
            return "/login";
        }
        else {
            List<List<String>> parentList = new ArrayList<>();

            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfAuthor);
            List<String> limitFields = new ArrayList<>();
            limitFields.add("_id");
            limitFields.add("name");
            limitFields.add("createtime");
            FindIterable<Document> findIterable = collection.find().projection(Projections.include(limitFields));
            MongoCursor<Document> cursor = findIterable.iterator();
            while (cursor.hasNext()) {
                Document doc = cursor.next();

                String id = doc.get("_id").toString();
                String name = doc.get("name").toString();
                String createTime = doc.get("createtime").toString();

                List<String> oneAuthor = new ArrayList<>();
                oneAuthor.add(id);
                oneAuthor.add(name);
                oneAuthor.add(createTime);

                parentList.add(oneAuthor);
            }
            cursor.close();

            long unread = NotifyHelper.countUnreadNotify(uuid);
            modelMap.put("unread", unread);
            modelMap.put("userName", account);
            modelMap.put("contentList", parentList);
            modelMap.put("year2year", TimeHelper.getFormattedYear2Year());
            return "admin/authorListPage";
        }
    }
}
